import http from 'wechat-http'
// 导入 http 模块

// 基础路径
http.baseURL = 'https://live-api.itheima.net'
//配置请求拦截器
http.intercept.request = function (options) {
  const defaultHeader = {}
  defaultHeader.Authorization = 'Bearer ' + getApp().token
  options.header = Object.assign({}, defaultHeader, options.header)
  return options
}
//配置响应拦截器
http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    // 获取应用实例来读取
    const app = getApp()
    //状态码401且接口为refreshToken 表示都过期了
    if (config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack.pop()
      const redirectURL = currentPage.route
      //跳转登录页
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/' + redirectURL,
      })
    }
    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken,
      },
    })
    // 检测接口是否调用成功
    if (res.code !== 10000) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
      return wx.utils.toast('更新token失败!')
    }
    // 重新存储新的 token
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    config = Object.assign(config, {
      header: {
        // 更新后的 token
        Authorization: 'Bearer ' + res.data.token,
      },
    })
    // 重新发请求
    return http(config)
  }
  return data
}
// 挂载到全局对象
wx.http = http
// 普通的模块导出
export default http
